<template>
  <div class="app-container xjAdd">
    <el-form :model="formParams" :rules="rules" ref="formParams" label-width="120px" class="demo-formParams">
      <p>新增巡检</p>
      <el-card class="margin-bottom-15">
        <el-descriptions title="基本信息" :column="3" border></el-descriptions>
        <el-row>
          <el-col :span="8">
            <el-form-item label="场所名称" prop="placeCode" :rules="[{ required: true, message: '请选择场所' }]">
              <el-select clearable v-model="formParams.placeCode" @change="changePlaceCode">
                <el-option v-for="item in placeList" :key="item.placeCode" :value="item.placeCode" :label="item.placeName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房源名称" prop="roomId" :rules="[{ required: true, message: '请选择房源' }]">
              <el-select clearable v-model="formParams.roomId" @change="changeRoomCode">
                <el-option v-for="item in roomList" :key="item.houseCode" :value="item.houseCode" :label="item.roomName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="margin-bottom-15">
        <el-descriptions title="房间问题" :column="3" border></el-descriptions>
        <el-row>
          <el-col :span="24">
            <el-form-item label="存在的问题" prop="roomProblem">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4}"
                placeholder="请输入存在的问题"
                v-model="formParams.roomProblem" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片">
              <el-upload
                action="#"
                list-type="picture-card"
                :on-remove="handleRemove"
                :file-list="fileList"
                :auto-upload="false"
                :on-change="changeFileList">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="margin-bottom-15">
        <el-descriptions title="加扣分明细" border>
          <template slot="extra">
            <el-button type="primary" size="small" @click="addJfxItem">新增</el-button>
          </template>
        </el-descriptions>
        <el-table :data="scoreList">
          <el-table-column label="类型" align="center" prop="scoreType">
            <template slot-scope="scope">
              <div v-show="scope.row.isEdit">
                <el-select clearable v-model="scope.row.scoreType" @change="changeScoreType(scope.row.scoreType, scope.row)">
                  <el-option v-for="item in jkflxList" :key="item.value" :value="item.text" :label="item.text"></el-option>
                </el-select>
              </div>
              <div v-show="!scope.row.isEdit">
                <span>{{ scope.row.scoreType }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="加分明细" align="center" prop="scoreItem" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div v-show="scope.row.isEdit">
                <el-select clearable v-model="scope.row.scoreItem">
                  <el-option v-for="item in jkfxzList" :key="item.value" :value="item.label" :label="item.label"></el-option>
                </el-select>
              </div>
              <div v-show="!scope.row.isEdit">
                <span>{{ scope.row.scoreItem }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="加分说明" align="center" prop="scoreRemark">
            <template slot-scope="scope">
              <div v-show="scope.row.isEdit">
                <el-input
                type="textarea"
                :autosize="{ minRows: 1}"
                placeholder="请输入加分说明"
                v-model="scope.row.scoreRemark" />
              </div>
              <div v-show="!scope.row.isEdit">
                <span>{{ scope.row.scoreRemark }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="score" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div v-show="scope.row.isEdit">
                <el-input
                placeholder="请输入分值"
                v-model="scope.row.score" />
              </div>
              <div v-show="!scope.row.isEdit">
                <span>{{ scope.row.score }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="editRow(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                @click="sureRow(scope.row)"
              >确认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="margin-bottom-15">
        <el-descriptions title="挂牌" border></el-descriptions>
        <el-row>
          <el-col :span="8">
            <el-form-item label="挂牌类型" prop="cardType">
              <el-select clearable v-model="formParams.cardType" @change="changeGplx(formParams.cardType, formParams)">
                <el-option v-for="item in gplxList" :key="item" :value="item" :label="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="挂牌细则" prop="cardItem" :rules="[{ required : formParams.cardType ? true : false, message: '请选择挂牌细则' }]">
              <el-select clearable v-model="formParams.cardItem">
                <el-option v-for="item in gpxzList" :key="item.label" :value="item.label" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="挂牌说明" prop="cardBz" :rules="[{ required: formParams.cardType ? true : false, message: '请输入挂牌说明' }]">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2}"
                placeholder="请输入挂牌说明"
                v-model="formParams.cardBz" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="整改开始时间" prop="rectStartTime" :rules="[{ required : formParams.cardType ? true : false, message: '请选择整改开始时间' }]">
              <el-date-picker
                v-model="formParams.rectStartTime"
                type="date"
                placeholder="请选择整改开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="整改结束时间" prop="rectEndTime" :rules="[{ required : formParams.cardType ? true : false, message: '请选择整改结束时间' }]">
              <el-date-picker
                v-model="formParams.rectEndTime"
                type="date"
                placeholder="请选择整改结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="margin-bottom-15">
        <el-descriptions title="事件反馈" border>
          <template slot="extra">
            <el-button type="primary" size="small" @click="addSjfk">新增</el-button>
          </template>
        </el-descriptions>
        <el-table :data="formParams.eventList">
          <el-table-column label="事件内容" align="center" prop="eventContent" :rules="[{ required : true, message: '请填写事件内容' }]">
            <template slot-scope="scope">
              <div v-show="scope.row.isEdit">
                <el-input
                type="textarea"
                :autosize="{ minRows: 1}"
                placeholder="请输入事件内容"
                v-model="scope.row.eventContent" />
              </div>
              <div v-show="!scope.row.isEdit">
                <span>{{ scope.row.eventContent }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center" prop="score">
            <template slot-scope="scope">
              <div>
                <el-image v-for="(sitem, sindex) in scope.row.fileList" :key="sindex" :src="'/api' + sitem.filename"></el-image>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="editRow(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                @click="sureRow(scope.row)"
              >确认</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </el-card>

      <el-form-item style="text-align: center; margin-left: 0">
        <el-button type="primary" @click="submitForm('formParams')">新增巡检</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="新增事件反馈"
      :visible.sync="handleSjfkVisible"
      width="40%"
    >
      <el-form label-position="right" label-width="80px" :model="eventObj" ref="ruleForm">
        <el-form-item label="事件内容">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4}"
            placeholder="请输入事件内容"
            v-model="eventObj.eventContent"
            :rules="[{ required: true, message: '请输入事件内容' }]"
            required />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="/api/common/upload"
            list-type="picture-card"
            :on-change="changeSjFileList"
            :auto-upload="false"
            :file-list="sjfkFileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dealSjkfList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { upload } from '@/api/common';
import { getPlace,listPlace } from '@/api/ptsj/place';
import { listInfo } from '@/api/ptsj/info';
import { addInspection } from '@/api/ptsj/inspection';

export default {
  name: 'add',
  dicts: ['ptsj_score_plus', 'ptsj_score_redution', 'ptsj_red_card_item', 'ptsj_yellow_card_item', 'ptsj_blue_card_item'],
  data() {
    return {
      formParams: {
        placeCode: '',
        placeName: '',
        roomId: '',
        roomName: '',
        roomProblem: '',
        cardType: '',
        cardItem: '',
        cardBz: '',
        rectStartTime: '',
        rectEndTime: '',
        eventList: []
      },
      fileList: [],
      sjfkFileList: [],
      fjBackList: [],
      rules: {
        roomProblem: [
          { required: true, message: '请输入存在的问题', trigger: 'blur' },
        ]
      },
      scoreList: [],
      jkflxList: [{ text: '加分', value: '1' }, { text: '扣分', value: '2' }],
      jkfxzList: [],
      gpxzList: [],
      gplxList: ['蓝牌', '黄牌', '红牌'],
      handleSjfkVisible: false,
      eventObj: { eventContent: '', fileList: [] }, //事件单个反馈
      roomList: [], // 房源列表
      placeInfo: {}, // 场所信息
      placeList: [], // 场所列表
    }
  },
  created() {
    this.listPlace();
  },
  methods: {
    changeRoomCode(val) {
      let dealData = this.roomList.filter(item => {
        if(item.houseCode == val) {
          return item
        }
      })
      if(dealData.length > 0) {
        this.formParams.placeName = dealData[0].placeName;
        this.formParams.roomName = dealData[0].roomName;
      }
    },
    changePlaceCode(data) {
      this.formParams.placeCode = data;
      this.formParams.roomId = '';
      this.getPlaceInfo()
      this.getRoomList(0) // 0 - 不需要地址栏上的默认值 1 需要
    },
    /** 查询场所信息列表 */
    listPlace() {
      listPlace({ pageNum: 1, pageSize: 9999 }).then(response => {
        this.placeList = response.rows;
        if(this.$route.query.placeCode) {
          this.$nextTick(() => {
            this.formParams.placeCode = this.$route.query.placeCode;
            this.getPlaceInfo()
            this.getRoomList(1)
          })
        }
      });
    },
    async getPlaceInfo() {
      await getPlace(this.$route.query.placeCode).then(res => {
        try {
          // console.log(res)
          if(res.code == 200) {
            this.placeInfo = res.data;
          }
        } catch {}
      })
    },
    async getRoomList(type){
      let params = {
        pageNum: 1,
        pageSize: 10,
        placeCode: null,
      };
      params.placeCode = this.formParams.placeCode;
      await listInfo(params).then(response=>{
        try{
          this.roomList = response.rows;
          if(this.$route.query.houseCode && type == 1) {
            this.$nextTick(() => {
              this.formParams.roomId = this.$route.query.houseCode;
              let dealData = this.roomList.filter(item => {
                if(item.houseCode == this.formParams.roomId) {
                  return item
                }
              })
              if(dealData.length > 0) {
                this.formParams.placeName = dealData[0].placeName;
                this.formParams.roomName = dealData[0].roomName;
              }
            })
          }
          // console.log(response.rows)
        } catch {}
      })
    },
    // 选择加扣分类型
    changeScoreType(val, row) {
      row.scoreItem = '';
      if(val == '加分') {
        this.jkfxzList = this.dict.type.ptsj_score_plus
      } else if(val == '扣分'){
        this.jkfxzList = this.dict.type.ptsj_score_redution
      } else {
        this.jkfxzList = []
      }
    },
    // 选择挂牌类型
    changeGplx(val, row) {
      row.cardItem = '';
      if(val == '红牌') {
        this.gpxzList = this.dict.type.ptsj_red_card_item
      } else if(val == '蓝牌') {
        this.gpxzList = this.dict.type.ptsj_blue_card_item
      } else if(val == '黄牌') {
        this.gpxzList = this.dict.type.ptsj_yellow_card_item
      } else {
        this.gpxzList = []
      }
    },
    // 新增加扣分
    addJfxItem() {
      this.scoreList.push({
        scoreType: '',
        scoreItem: '',
        scoreRemark: '',
        score: '',
        isEdit: true
      })
    },
    // 新增事件反馈
    addSjfk() {
      this.eventObj.eventContent = '';
      this.eventObj.sjfkFileList = [];
      this.sjfkFileList = [];
      this.handleSjfkVisible = true
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.fileList = fileList;
    },
    changeFileList(file, fileList) {
      this.fileList = fileList;
    },
    editRow(row) {
      row.isEdit = true;
    },
    sureRow(row) {
      row.isEdit = false;
    },
    changeSjFileList(file, fileList) {
      this.sjfkFileList = fileList;
    },
    // 事件反馈
    async handleSjFile() {
      if(this.sjfkFileList.length > 0) {
        for(let i= 0; i< this.sjfkFileList.length; i++) {
          let formData = new FormData();
          formData.append('file', this.sjfkFileList[i].raw);
          await upload(formData).then(response => {
            try {
              // 成功回调
              this.eventObj.fileList.push({
                filename: response.fileName,
                newfilename: response.newFileName,
                originalfilename: response.originalFilename,
                url: response.url,
              })
            } catch(error) {
              console.log(error)
            }
          })
        }
      }
    },
    async dealSjkfList() {
      await this.handleSjFile();
      this.formParams.eventList.push(this.eventObj);
      this.handleSjfkVisible = false
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.uploadImage();
          let params = this.formParams;
          params.placeCode = this.placeInfo.placeCode;
          params.roomName = this.formParams.roomName;
          params.placeName = this.placeInfo.placeName;
          params.inspFiles = this.fjBackList;
          params.scoreList = this.scoreList;
          // console.log(params)
          await addInspection(params).then(res => {
            // console.log(res)
            if(res.code == 200) {
              this.$message.success('新增成功!');
              this.fileList = []
              this.sjfkFileList = []
              this.fjBackList = []
              this.scoreList = []
              this.$refs.formParams.resetFields();
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async uploadImage() {
      if(this.fileList.length > 0) {
        for(let i= 0; i< this.fileList.length; i++) {
          let formData = new FormData();
          formData.append('file', this.fileList[i].raw);
          await upload(formData).then(res => {
            try {
              // console.log(res)
              this.fjBackList.push({
                filename: res.fileName,
                newfilename: res.newFileName,
                originalfilename: res.originalFilename,
                url: res.url,
              })
            } catch(error) {
              console.log(error)
            }
          })
        }
      }
    },
    // 清空数据
    clearFormParams() {
      this.formParams = {
        roomProblem: '',
        cardType: '',
        cardItem: '',
        cardBz: '',
        rectStartTime: '',
        rectEndTime: '',
        eventList: []
      },
      this.fileList = []
      this.sjfkFileList = []
      this.fjBackList = []
      this.scoreList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.margin-bottom-15 {
  margin-bottom: 15px;
  margin-bottom: 50px;
}
</style>

<style scoped>
.xjAdd >>> .el-descriptions__title {
  font-weight: normal;
  border-left: 4px solid rgb(110, 172, 238);
  padding-left: 15px;
}
.xjAdd >>> .el-form-item__label {
  font-weight: normal;
}
</style>